var express = require('express')
var app = express()
var http = require('http')
var config = require('./config')
var session = require('express-session')
var cookieParser = require('cookie-parser')
var T = require('./server/utils.js')

var bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

app.use(cookieParser())
app.use(session({
  name: 'nodejs_sid_portal',
  secret: config.sessionConfig.secret,
  resave: false,
  saveUninitialized: true,
  cookie: {
    secure: false, // true表示https
    domain: config.sessionConfig.domain
  }
}))

app.get('/health', function (req, res) {
  return res.status(200).send('OK')
})

// app.use("*",require('./server/checkLogin'));

var proxy = require('http-proxy-middleware')

// *! 最新
const options2 = {
  target: 'http://' + config.ajaxHost2,
  changeOrigin: true,
  onProxyReq: (proxyReq, req, res) => {
    console.log('最新poc转发地址proxy----', 'http://' + config.ajaxHost2 + req.path)
    if (req.path && req.path.indexOf('uploadFile') < 0) {
      proxyReq.setHeader('Content-Type', 'application/json')
    }
    proxyReq.setHeader('lang', req.cookies['lang'] || '')
    proxyReq.setHeader('userToken', req.session.userInfo && req.session.userInfo.userToken || '')
  },
  onProxyRes: (proxyRes, req, res) => {

  },
  pathRewrite: { '^/ajax2': '' }
}

const apiProxy2 = proxy(options2)
app.use(/^\/ajax2/i, apiProxy2)

// *! ajax
const options = {
  target: 'http://' + config.ajaxHost,
  changeOrigin: true,
  onProxyReq: (proxyReq, req, res) => {
    var timeStr = T.formatDate('yyyy-MM-dd hh:mm:ss', new Date())
    console.log('【' + timeStr + '】ajax转发地址proxy----', 'http://' + config.ajaxHost + req.path)

    if (req.path && req.path.indexOf('msg/claim/imageUpload') < 0) {
      proxyReq.setHeader('Content-Type', 'application/json')
    }

    proxyReq.setHeader('lang', req.cookies['lang'] || '')
    proxyReq.setHeader('userToken', req.session.userInfo && req.session.userInfo.userToken || '')
  },
  onProxyRes: (proxyRes, req, res) => {
    console.log('【res end】................')
  },
  pathRewrite: { '^/ajax': '' }
}

const apiProxy = proxy(options)

app.use(/^\/ajax/i, apiProxy) // ajax转发

// *! fusion poc
const fusion = {
  target: 'http://' + config.fusionHost,
  changeOrigin: true,
  onProxyReq: (proxyReq, req, res) => {
    console.log('fusion-poc转发地址proxy----', 'http://' + config.fusionHost + req.path)
    if (req.path && req.path.indexOf('uploadFile') < 0) {
      proxyReq.setHeader('Content-Type', 'application/json')
    }
    proxyReq.setHeader('lang', req.cookies['lang'] || '')
    proxyReq.setHeader('userToken', req.session.userInfo && req.session.userInfo.userToken || '')
  },
  onProxyRes: (proxyRes, req, res) => {

  },
  pathRewrite: { '^/fusion': '' }
}

const apiProxyfusion = proxy(fusion)
app.use(/^\/fusion/i, apiProxyfusion)

// *! 医生端
const optionsClaim = {
  target: 'http://' + config.claim + ':' + config.ajaxPort,
  changeOrigin: true,
  onProxyReq: (proxyReq, req, res) => {
    console.log('proxy----', 'http://' + config.claim + ':' + config.ajaxPort + req.path)
    if (req.path && req.path.indexOf('smartclaim/case/uploadImage') < 0) {
      proxyReq.setHeader('Content-Type', 'application/json')
    }
    proxyReq.setHeader('lang', req.cookies['lang'] || '')
    proxyReq.setHeader('userToken', req.session.userInfo && req.session.userInfo.userToken || '')
  },
  onProxyRes: (proxyRes, req, res) => {

  },
  pathRewrite: { '^/claim': '' }
}

const optionsClaim2 = {
  target: 'http://' + config.claim2 + ':' + config.ajaxPort,
  changeOrigin: true,
  onProxyReq: (proxyReq, req, res) => {
    console.log('proxy----', 'http://' + config.claim2 + ':' + config.ajaxPort + req.path)
    proxyReq.setHeader('Content-Type', 'application/json')
    proxyReq.setHeader('lang', req.cookies['lang'] || '')
    proxyReq.setHeader('userToken', req.session.userInfo && req.session.userInfo.userToken || '')
  },
  onProxyRes: (proxyRes, req, res) => {

  },
  pathRewrite: { '^/claim': '' }
}

const apiProxyClaim = proxy(optionsClaim)
const apiProxyClaim2 = proxy(optionsClaim2)
app.use(/^\/claim\/component\/emum\/list/i, apiProxyClaim2)
app.use(/^\/claim/i, apiProxyClaim)

// 电子保单和发票的转发
var optionTranslate = {
  target: 'http://' + config.fileHost + ':' + config.ajaxPort,
  changeOrigin: true,
  onProxyReq: (proxyReq, req, res) => {
    console.log('proxy----', 'http://' + config.claim2 + ':' + config.ajaxPort + req.path)
    proxyReq.setHeader('Content-Type', 'application/json')
    proxyReq.setHeader('lang', req.cookies['lang'] || '')
    proxyReq.setHeader('userToken', req.session.userInfo && req.session.userInfo.userToken || '')
  },
  onProxyRes: (proxyRes, req, res) => {

  },
  pathRewrite: { '^/translateHost': '' }
}
var apiProxyTranslate = proxy(optionTranslate)

app.use(/^\/translateHost/i, apiProxyTranslate)

// begin ------> 理赔系统接口调用
const requestProxy = proxy({
  target: 'http://' + config.apiClaim,
  changeOrigin: true,
  onProxyReq: (proxyReq, req, res) => {
    console.log('理赔代理转发------->', 'http://' + config.apiClaim + req.path)
    if (req.path && req.path.indexOf('uploadFile') < 0) {
      proxyReq.setHeader('Content-Type', 'application/json')
    }
    proxyReq.setHeader('lang', req.cookies['lang'] || '')
  },
  onProxyRes: (proxyRes, req, res) => {

  },
  pathRewrite: { '^/apiclaim': '' }
})
app.use(/^\/apiclaim/i, requestProxy)
// end   ------> 理赔系统接口调用

// *! 国际化的转发
var guojihuaTranslate = {
  target: 'http://' + config.i18nHost,
  changeOrigin: true,
  onProxyReq: (proxyReq, req, res) => {
    console.log('国际化转发地址proxy----', 'http://' + config.i18nHost + req.path)
    // proxyReq.setHeader('Content-Type', 'application/json')
  },
  onProxyRes: (proxyRes, req, res) => {

  },
  pathRewrite: { '^/guojihua': '' }
}
var guojihua = proxy(guojihuaTranslate)

app.use(/^\/guojihua/i, guojihua)

app.use('/', require('connect-history-api-fallback')())
app.use('/', express.static('public'))

app.use('/favicon.ico', function (req, res) {
  res.end()
})

if (process.env.NODE_ENV === 'dev') {
  var webpack = require('webpack')
  var webpackConfig = require('./build/webpack.dev.config.js')
  var webpackCompiled = webpack(webpackConfig)

  // 配置运行时打包
  var webpackDevMiddleware = require('webpack-dev-middleware')
  app.use(webpackDevMiddleware(webpackCompiled, {
    publicPath: '/',
    stats: { colors: true },
    lazy: false,
    hot: true,
    watchOptions: {
      aggregateTimeout: 200
    }
  }))

  // 配置热更新
  var webpackHotMiddleware = require('webpack-hot-middleware')
  app.use(webpackHotMiddleware(webpackCompiled))
}

http.createServer(app).listen(config.port, function () {
  console.log('Open http://localhost:%s', config.port)
})
